package com.cloudxingkong.dianyinke.NewTeacher.Utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;

/**
 * Created by LeeQ on 2016-4-28.
 */
public class LocationUtils {

    public static HashMap<String,String> getLocation(Context context) {
        String locationProvider = "";

        LocationManager manager = ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE));
        List<String> providers = manager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是NetWork
            locationProvider = LocationManager.GPS_PROVIDER;
        } else {
            Toast.makeText(context, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return null;
        }

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        } else {
            Location location = manager.getLastKnownLocation(locationProvider);
            if (location != null) {
                HashMap<String, String> hashMap = showLocation(location);
                return hashMap;
            }
        }

        return null;
    }

    private static HashMap<String,String> showLocation(Location location) {
        HashMap<String,String> map=new HashMap<>();
        map.put("latitude",location.getLatitude()+"");
        map.put("longitude",location.getLongitude()+"");
        return map;
    }

    LocationListener locationListener=new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            showLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

}
